﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;

namespace PicHunter.Task.Impl
{
    public class DownloadPicTask //: Task
    {
        private Logging.Log LOG = Logging.Log.Instance;
        
        public String URL { get; set; }
        public String DIR { get; set; }
        public event TaskCompleted Completed;

        public DownloadPicTask()
        {
        }

        public void DoWork()
        {
            if (URL == null) URL = "";

            // filename
            int pos = URL.LastIndexOf("/") + 1;
            string filename = URL.Substring(pos);
            string filepath = String.Format(@"{0}\{1}", DIR, filename);

            if (File.Exists(filepath))
            {
                LOG.Debug(String.Format("{0} aready exits, skip", filename));
                return;
            }

            WebClient client = new WebClient();

            try
            {
                client.DownloadFile(URL, filepath);
            }
            catch (Exception ex)
            {
                LOG.Error(ex.Message);
                return;
            }
            
            LOG.Info("Download " + URL + " Completed");

            if (Completed != null)
            {
                Completed();
            }
        }
    }
}
